package com.xht.authorization.server.oauth2.server.authorization;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.util.Assert;

import java.security.Principal;

/**
 * <h1>描述 ： 用于管理新的和现有的授权许可</h1>
 * <h2>它是存储新授权同意和查询现有授权同意的中心组件。</h2>
 * <li>例如，
 *      <ol>它主要由实现OAuth2授权请求流的组件使用</ol>
 * </li>
 *
 * @author : 小糊涂
 * @version : 1.0
 * @see OAuth2AuthorizationConsent
 **/
@Slf4j
@RequiredArgsConstructor
public class XhtOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {

    private static final InMemoryOAuth2AuthorizationConsentService SERVICE = new InMemoryOAuth2AuthorizationConsentService();

    /**
     * 保存授权许可 {@link OAuth2AuthorizationConsent}.
     *
     * @param authorizationConsent {@link OAuth2AuthorizationConsent}
     */
    @Override
    public void save(OAuth2AuthorizationConsent authorizationConsent) {
        log.info("保存授权许可 {}",authorizationConsent);
        SERVICE.save(authorizationConsent);
    }

    /**
     * 删除授权许可 {@link OAuth2AuthorizationConsent}.
     *
     * @param authorizationConsent {@link OAuth2AuthorizationConsent}
     */
    @Override
    public void remove(OAuth2AuthorizationConsent authorizationConsent) {
        log.info("删除授权许可 {}",authorizationConsent);
        SERVICE.remove(authorizationConsent);
    }

    /**
     * 返回指定的授权许可 {@link OAuth2AuthorizationConsent}
     * {@code registeredClientId}和{@code principalName}，如果没有找到，则{@code null}。
     *
     * @param registeredClientId 客户端标识符  {@link RegisteredClient}
     * @param principalName      the name of the {@link Principal}
     * @return 如果找到，则返回{@link OAuth2AuthorizationConsent}，否则返回{@code null}
     */
    @Override
    public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
        Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
        Assert.hasText(principalName, "principalName cannot be empty");
        log.info("根据客户端id registeredClientId = {} , principalName = {} 返回指定的授权许可",registeredClientId,principalName);
        return SERVICE.findById(registeredClientId, principalName);
    }
}
